package com.sim.server.command.handler;

import com.sim.core.ImChannelContext;
import com.sim.core.ImConst;
import com.sim.core.ImPacket;
import com.sim.core.ImStatus;
import com.sim.core.cache.redis.JedisTemplate;
import com.sim.core.exception.ImException;
import com.sim.core.packets.Command;
import com.sim.core.packets.ForbiddenWordsReqBody;
import com.sim.core.packets.RespBody;
import com.sim.core.packets.StreamMessageBody;
import com.sim.core.utils.JsonKit;
import com.sim.core.utils.ValidateUtil;
import com.sim.core.utils.ValidationResult;
import com.sim.server.SimServerAPI;
import com.sim.server.command.AbstractCmdHandler;
import com.sim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description 上下麦
 * @Author yzf
 * @Date 2021/8/10
 * @Version 1.0
 **/
public class StreamMessageReqHandler extends AbstractCmdHandler {

    private static Logger log = LoggerFactory.getLogger(ForbiddenWordsReqHandler.class);

    @Override
    public ImPacket handler(ImPacket imPacket, ImChannelContext imChannelContext) throws ImException {
        if (imPacket.getBody() == null) {
            RespBody respBody = new RespBody(Command.COMMAND_STREAM_RESP, ImStatus.C10034);
            return ProtocolManager.Converter.respPacket(respBody, imChannelContext);
        }
        StreamMessageBody message = JsonKit.toBean(imPacket.getBody(), StreamMessageBody.class);
        ValidationResult validationResult = ValidateUtil.validateEntity(message);
        if (validationResult.isHasErrors()){
            RespBody respBody = new RespBody(Command.COMMAND_STREAM_RESP, ImStatus.C10034.getCode(), validationResult.randomErrorMsg());
            return ProtocolManager.Converter.respPacket(respBody, imChannelContext);
        }
        //todo 判断用户是否有上下麦的操作权限，暂时不处理

        ImPacket chatPacket = new ImPacket(Command.COMMAND_STREAM_REQ,new RespBody(Command.COMMAND_STREAM_REQ,message).toByte());
        //设置同步序列号;
        chatPacket.setSynSeq(imPacket.getSynSeq());
        if(message.getIsSystem()){
            SimServerAPI.sendToGroup(message.getGroupId(), chatPacket);
        }else {
            SimServerAPI.sendToUser(message.getUserId(), chatPacket);
        }
        //发送成功响应包
        return ProtocolManager.Packet.success(imChannelContext);
    }

    @Override
    public Command command() {
        return Command.COMMAND_STREAM_REQ;
    }
}
